//
// Created by ct on 2021/9/16.
//

#include "lib/common.h"

int main(int argc, char *argv[]) {
    int sockfd;
    struct sockaddr_un servaddr;
    sockfd = socket(AF_LOCAL, SOCK_STREAM, 0);
    if (sockfd < 0) { error(1, errno, "create socket failed"); }
    char *local_path = "/home/ct/unixstream.sock";
    bzero(&servaddr, sizeof(servaddr));
    servaddr.sun_family = AF_LOCAL;
    strcpy(servaddr.sun_path, local_path);
    if (connect(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0) { error(1, errno, "connect failed"); }
    char send_line[MAXLINE];
    bzero(send_line, MAXLINE);
    char recv_line[MAXLINE];
    while (fgets(send_line, MAXLINE, stdin) != NULL) {
        int nbytes = sizeof(send_line);
        if (write(sockfd, send_line, nbytes) != nbytes) error(1, errno, "write error");
        if (read(sockfd, recv_line, MAXLINE) == 0) error(1, errno, "server terminated prematurely");
        fputs(recv_line, stdout);
    }
    exit(0);
}